<?php
namespace app\controller;

use app\BaseController;
use app\common\TokenAuth;
use think\facade\Db;
use think\facade\Request;
use think\Response;

class MyApprovals extends BaseController
{
    /**
     * 获取待我审批列表
     * 支持按状态筛选、关键字搜索、审批类型筛选和日期范围筛选
     */
    public function getList()
    {
        // 验证token并获取用户信息
        $user = TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取分页参数
        $page = Request::param('page/d', 1);
        $limit = Request::param('limit/d', 10);
        $status = Request::param('status/d'); // 可选的状态筛选
        $keyword = Request::param('keyword/s', ''); // 关键字搜索
        $flowId = Request::param('flowId/d'); // 审批类型筛选
        $startDate = Request::param('startDate/s', ''); // 开始日期
        $endDate = Request::param('endDate/s', ''); // 结束日期

        // 构建查询
        $query = Db::name('approval_record')
            ->alias('r')
            ->join('approval_flow f', 'r.flow_id = f.id')
            ->join('user u', 'r.user_id = u.id')
            ->where('r.approver_id', $user['id']);

        // 如果指定了状态，添加状态筛选
        if (!is_null($status)) {
            $query = $query->where('r.status', $status);
        }
        
        // 关键字搜索（按申请人姓名）
        if (!empty($keyword)) {
            $query = $query->where('u.realname', 'like', "%{$keyword}%");
        }
        
        // 审批类型筛选
        if (!empty($flowId)) {
            $query = $query->where('r.flow_id', $flowId);
        }
        
        // 日期范围筛选
        if (!empty($startDate)) {
            $query = $query->where('r.create_time', '>=', $startDate . ' 00:00:00');
        }
        
        if (!empty($endDate)) {
            $query = $query->where('r.create_time', '<=', $endDate . ' 23:59:59');
        }

        // 获取总记录数
        $total = $query->count();

        // 获取分页数据
        $list = $query
            ->field([
                'r.id',
                'r.flow_id',
                'f.title as flow_title',
                'r.form_data',
                'r.status',
                'u.realname as applicant_name',
                'r.approve_time',
                'r.approve_remark',
                'r.create_time'
            ])
            ->order('r.create_time', 'desc') // 按创建时间倒序排列
            ->page($page, $limit)
            ->select();

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'total' => $total,
                'list' => $list
            ]
        ]);
    }

    /**
     * 处理审批
     * 同意或驳回审批申请
     */
    public function process()
    {
        // 验证token并获取用户信息
        $user = TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $id = Request::param('id/d');
        $action = Request::param('action/d'); // 2同意 3驳回
        $remark = Request::param('remark/s', '');

        // 参数验证
        if (empty($id) || !in_array($action, [2, 3])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 查询审批记录
        $record = Db::name('approval_record')
            ->where('id', $id)
            ->where('approver_id', $user['id'])
            ->where('status', 1) // 只能处理待审批的记录
            ->find();
            
        if (!$record) {
            return json(['code' => 400, 'msg' => '审批记录不存在或已处理']);
        }

        // 更新审批记录
        try {
            $result = Db::name('approval_record')
                ->where('id', $id)
                ->update([
                    'status' => $action,
                    'approve_time' => date('Y-m-d H:i:s'),
                    'approve_remark' => $remark
                ]);

            if ($result) {
                // 如果审批通过，检查是否为请假类型并同步请假记录
                if ($action == 2) {
                    // 添加调试日志
                    /*
                    file_put_contents(__DIR__ . '/myapprovals_debug_' . date('Y-m-d') . '.log', 
                        "[" . date('Y-m-d H:i:s') . "] 审批通过，开始调用LeaveApprovalService\n" . 
                        "传递的record数据: " . json_encode($record, JSON_UNESCAPED_UNICODE) . "\n", 
                        FILE_APPEND | LOCK_EX);
                    */
                    $leaveService = new \app\service\LeaveApprovalService();
                    $serviceResult = $leaveService->handleApprovalPassed($record);
                    /*
                    file_put_contents(__DIR__ . '/myapprovals_debug_' . date('Y-m-d') . '.log', 
                        "[" . date('Y-m-d H:i:s') . "] LeaveApprovalService调用结果: " . ($serviceResult ? '成功' : '失败') . "\n", 
                        FILE_APPEND | LOCK_EX);
                    */
                }
                
                return json(['code' => 200, 'msg' => '处理成功', 'data' => null]);
            } else {
                return json(['code' => 500, 'msg' => '处理失败', 'data' => null]);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取审批详情
     */
    public function detail()
    {
        // 验证token并获取用户信息
        $user = TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }

        // 获取请求参数
        $id = Request::param('id/d');
        
        // 参数验证
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }

        // 查询审批记录
        $record = Db::name('approval_record')
            ->alias('r')
            ->join('approval_flow f', 'r.flow_id = f.id')
            ->join('user u1', 'r.user_id = u1.id')
            ->join('user u2', 'r.approver_id = u2.id')
            ->where('r.id', $id)
            ->where(function($query) use ($user) {
                // 只能查看自己提交的或者自己审批的记录
                $query->where('r.user_id', $user['id'])
                      ->whereOr('r.approver_id', $user['id']);
            })
            ->field([
                'r.id',
                'r.flow_id',
                'f.title as flow_title',
                'r.form_data',
                'r.status',
                'u1.realname as applicant_name',
                'u2.realname as approver_name',
                'r.approve_time',
                'r.approve_remark',
                'r.create_time'
            ])
            ->find();
            
        if (!$record) {
            return json(['code' => 404, 'msg' => '审批记录不存在']);
        }

        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $record
        ]);
    }

    /**
     * 生成请假打卡记录
     * 当请假审批通过时，自动为请假时间段生成对应的打卡记录
     */
    private function generateLeaveAttendanceRecords($record)
    {
        try {
            // 查询审批流程是否为请假类型
            $flow = Db::name('approval_flow')
                ->where('id', $record['flow_id'])
                ->where('is_leave_type', 1)
                ->find();
            
            if (!$flow) {
                return; // 不是请假类型，直接返回
            }

            // 解析请假时间
            $leaveTime = $this->parseLeaveTime($record['flow_id'], $record['form_data']);
            if (!$leaveTime) {
                return; // 无法解析请假时间
            }

            // 获取考勤设置
            $attendanceSettings = $this->getAttendanceSettings();
            if (!$attendanceSettings) {
                return; // 无法获取考勤设置
            }

            // 生成请假期间的打卡记录
            $this->createLeaveRecords($record['user_id'], $leaveTime, $attendanceSettings);

        } catch (\Exception $e) {
            // 记录错误日志，但不影响审批流程
            //error_log('生成请假打卡记录失败: ' . $e->getMessage());
        }
    }

    /**
     * 解析请假时间
     */
    private function parseLeaveTime($flowId, $formDataJson)
    {
        $formData = json_decode($formDataJson, true);
        if (!$formData) {
            return null;
        }

        // 获取审批流程的字段定义
        $fields = Db::name('approval_flow_field')
            ->where('flow_id', $flowId)
            ->where('field_type', 'datetime')
            ->order('sort', 'asc')
            ->select();

        if (count($fields) < 2) {
            return null; // 至少需要两个时间字段
        }

        $startTime = null;
        $endTime = null;

        // 方法1: 通过字段名称关键词识别
        foreach ($fields as $field) {
            $fieldValue = $formData['field_' . $field['id']] ?? null;
            if (!$fieldValue) continue;

            if (strpos($field['field_name'], '开始') !== false || strpos($field['field_name'], '起始') !== false) {
                $startTime = $fieldValue;
            } elseif (strpos($field['field_name'], '结束') !== false || strpos($field['field_name'], '截止') !== false) {
                $endTime = $fieldValue;
            }
        }

        // 方法2: 如果关键词识别失败，按时间先后顺序
        if (!$startTime || !$endTime) {
            $times = [];
            foreach ($fields as $field) {
                $fieldValue = $formData['field_' . $field['id']] ?? null;
                if ($fieldValue) {
                    $times[] = $fieldValue;
                }
            }

            if (count($times) >= 2) {
                sort($times);
                $startTime = $times[0];
                $endTime = $times[1];
            }
        }

        if (!$startTime || !$endTime) {
            return null;
        }

        return [
            'start_time' => $startTime,
            'end_time' => $endTime
        ];
    }

    /**
     * 获取考勤设置
     */
    private function getAttendanceSettings()
    {
        $settings = Db::name('attendance_settings')
            ->where('id', 1)
            ->find();

        return $settings;
    }

    /**
     * 创建请假记录
     */
    private function createLeaveRecords($userId, $leaveTime, $settings)
    {
        $startDate = date('Y-m-d', strtotime($leaveTime['start_time']));
        $endDate = date('Y-m-d', strtotime($leaveTime['end_time']));
        
        $currentDate = $startDate;
        
        while ($currentDate <= $endDate) {
            // 检查是否已存在该日期的考勤记录
            $existingRecord = Db::name('attendance_record')
                ->where('user_id', $userId)
                ->where('date', $currentDate)
                ->find();

            if (!$existingRecord) {
                // 创建新的请假打卡记录
                $recordData = [
                    'user_id' => $userId,
                    'date' => $currentDate,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ];

                // 根据工作类型设置请假状态
                if ($settings['work_type'] == 1) {
                    // 一天一次打卡
                    $recordData['morning_check_in_status'] = 5; // 请假
                } else {
                    // 一天两次打卡
                    $recordData['morning_check_in_status'] = 5; // 请假
                    $recordData['morning_check_out_status'] = 5; // 请假
                    
                    // 如果有下午打卡
                    if (!empty($settings['afternoon_check_in_time'])) {
                        $recordData['afternoon_check_in_status'] = 5; // 请假
                        $recordData['afternoon_check_out_status'] = 5; // 请假
                    }
                }

                Db::name('attendance_record')->insert($recordData);
            } else {
                // 更新现有记录的状态为请假
                $updateData = [];
                
                if ($settings['work_type'] == 1) {
                    $updateData['morning_check_in_status'] = 5;
                } else {
                    $updateData['morning_check_in_status'] = 5;
                    $updateData['morning_check_out_status'] = 5;
                    
                    if (!empty($settings['afternoon_check_in_time'])) {
                        $updateData['afternoon_check_in_status'] = 5;
                        $updateData['afternoon_check_out_status'] = 5;
                    }
                }
                
                $updateData['update_time'] = date('Y-m-d H:i:s');
                
                Db::name('attendance_record')
                    ->where('id', $existingRecord['id'])
                    ->update($updateData);
            }

            // 下一天
            $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
        }
    }
} 